import time
import requests
# import json
import traceback
xmlForm ="""
	<xml>
	<ToUserName><![CDATA[%s]]></ToUserName>
	<FromUserName><![CDATA[%s]]></FromUserName>
	<CreateTime>%s</CreateTime>
	<MsgType><![CDATA[text]]></MsgType>
	<Content><![CDATA[%s]]></Content>
	</xml>
"""
def send_text(data):
    try:
        print('the data FROM users',data)
    	# %s 字符串占位符，数量要一致
    	# 响应用户消息时，要注意fromuser,touser的角色已互换，所以两个变量的次序要互换，任何错误都会导致无法响应用户消息
        url = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg='+data['content']
    	# requests.get返回response对象，json方法可将response对象直接返回字典
        answer = requests.get(url)
        if answer.json()['result'] == 0 and answer.status_code == 200:
            reply = answer.json()['content']
        else:
            reply = '我很忙，请晚点再来找我'    
        response = xmlForm % (data['from'],data['to'],str(int(time.time())),reply)
        print('the data FOR user',response)
        print('Deal with the TEXT data from users successfully and send to wechat server')
        return response
    except Exception as e:
    # 导入traceback模块，打印更详细的异常信息，有利于调试程序
        traceback.print_exc()

def noType(data):
    try:
        print('the data FROM users',data)
        response = xmlForm % (data['from'],data['to'],str(int(time.time())),'该类型尚未开发，敬请期待吧！')
        print('the data FOR user',response)
        print('Deal with the TEXT data from users successfully and send to wechat server')
        return response
    except Exception as e:
        traceback.print_exc()
